package com.ja.openchat.ui.chat.call;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import androidx.lifecycle.ViewModelProviders;

import com.blankj.utilcode.util.BarUtils;
import com.google.gson.JsonObject;
import com.gyf.immersionbar.ImmersionBar;
import com.zy.openchat.App;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.call.CallManager;
import com.zy.openchat.core.model.user.UserInfo;
import com.ja.openchat.databinding.ActivityC2cCallBinding;
import com.zy.openchat.util.LocalNotificationHelper;
import com.ja.openchat.viewmodels.C2CActivityViewModel;

import java.util.Map;

import io.agora.rtc.RtcEngine;
import jp.wasabeef.blurry.Blurry;
import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class C2CCallActivity extends BaseActivity<ActivityC2cCallBinding, C2CActivityViewModel> implements View.OnClickListener {

    private PowerManager.WakeLock wakeLock = null;
    //视频通话界面相关
    private boolean smallVideoViewIsTarget;

    public static void start(Context context, boolean isNewIncoming) {
        Intent intent = new Intent();
        intent.setClass(context, C2CCallActivity.class);
        if (!(context instanceof Activity)) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra("isNewIncoming", isNewIncoming);
        context.startActivity(intent);
    }


    @Override
    public void initView() {
        super.initView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            setShowWhenLocked(true);
        } else {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        }
        ((ViewGroup.MarginLayoutParams)binding.ivBarBack.getLayoutParams()).topMargin = ImmersionBar.getStatusBarHeight(this);
        viewModel.setContext(this);
        binding.toolbarAudioSpeaker.setOnClickListener(this);
        binding.toolbarAudioMute.setOnClickListener(this);
        binding.toolbarAudioHangup.setOnClickListener(this);
        binding.toolbarVideoToggleCamera.setOnClickListener(this);
        binding.toolbarVideoHangup.setOnClickListener(this);
        binding.toolbarIncomingAccept.setOnClickListener(this);
        binding.toolbarIncomingHangup.setOnClickListener(this);
        binding.videoCallSmallVideoView.setOnClickListener(this);
        binding.ivBarBack.setOnClickListener(this);

        resetCallUI();
        resetC2CUserUI();

        if (getIntent() != null) {
            if (getIntent().getBooleanExtra("isNewIncoming", false)) {
                //播放来电音乐
                LocalNotificationHelper.playIncoming(App.getInstanse());
                LocalNotificationHelper.PhoneVibrator(App.getInstanse());
                //是否锁屏
                KeyguardManager mKeyguardManager = (KeyguardManager) App.getInstanse().getSystemService(Context.KEYGUARD_SERVICE);
                boolean locked = mKeyguardManager.inKeyguardRestrictedInputMode();
                if (locked) {//锁屏
                    PowerManager pm = (PowerManager) App.getInstanse().getSystemService(Context.POWER_SERVICE);
                    @SuppressLint("InvalidWakeLockTag")
                    PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "incoming");
                    wakeLock.acquire();
                    wakeLock.release();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (CallManager.getCallManager().isInCalling()) {
            CallManager.getCallManager().showSmallTopView();
        }
    }
    @Override
    public void setStatusBar() {
        BarUtils.setStatusBarLightMode(this, false);
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
    }


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_c2c_call;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public C2CActivityViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(C2CActivityViewModel.class);
    }

    private void makeContentLayoutVisible(boolean showContentLayout, boolean showToolbar, boolean showIncomingToolbar) {
        if (showContentLayout) {
            if (CallManager.getCallManager().isVideo()) {
                binding.videoCallLayout.setVisibility(View.VISIBLE);
                binding.voiceCallLayout.setVisibility(View.GONE);
            } else {
                binding.videoCallLayout.setVisibility(View.GONE);
                binding.voiceCallLayout.setVisibility(View.VISIBLE);
            }
        } else {
            binding.videoCallLayout.setVisibility(View.GONE);
            binding.voiceCallLayout.setVisibility(View.GONE);
        }

        if (showToolbar) {
            if (CallManager.getCallManager().isVideo()) {
                binding.toolbarVideoLayout.setVisibility(View.VISIBLE);
                binding.toolbarAudioLayout.setVisibility(View.GONE);
            } else {
                binding.toolbarVideoLayout.setVisibility(View.GONE);
                binding.toolbarAudioLayout.setVisibility(View.VISIBLE);
            }
        } else {
            binding.toolbarVideoLayout.setVisibility(View.GONE);
            binding.toolbarAudioLayout.setVisibility(View.GONE);
        }

        if (showIncomingToolbar) {
            binding.toolbarIncomingLayout.setVisibility(View.VISIBLE);
        } else {
            binding.toolbarIncomingLayout.setVisibility(View.GONE);
        }
    }

    public void resetCallUI() {
        if (CallManager.getCallManager().isInCalling()) {
            binding.videoCallHeaderImageView.setVisibility(View.VISIBLE);
            binding.videoCallDisplaynameText.setVisibility(View.VISIBLE);
//            binding.videoCallTimeText.setVisibility(View.VISIBLE);
//            binding.voiceCallTimeText.setVisibility(View.VISIBLE);
            switch (CallManager.getCallManager().currentCallState()) {
                case CallingState_Init: {
                    //隐藏时间
                    binding.videoCallTimeText.setVisibility(View.GONE);
                    binding.voiceCallTimeText.setVisibility(View.GONE);
                    if (CallManager.getCallManager().isIncoming()) {//来电
                        makeContentLayoutVisible(true, false, true);
                        if (CallManager.getCallManager().isVideo()) {
                            binding.videoCallStateText.setText(getString(R.string.phone_stats_video_yaoqing));
                        } else {
                            binding.voiceCallStateText.setText(getString(R.string.phone_stats_voice_yaoqing));
                        }
                    } else {//呼出
                        makeContentLayoutVisible(true, true, false);
                        if (CallManager.getCallManager().isVideo()) {
                            binding.videoCallStateText.setText(getString(R.string.phone_stats_video_preparing));
                        } else {
                            binding.voiceCallStateText.setText(getString(R.string.phone_stats_voice_preparing));
                        }
                    }
                }
                break;
                case CallingState_Outgoing_Prepare:
                case CallingState_Outgoing_Prepare_error: {
                    //隐藏时间
                    binding.videoCallTimeText.setVisibility(View.GONE);
                    binding.voiceCallTimeText.setVisibility(View.GONE);
                    makeContentLayoutVisible(true, true, false);
                    if (CallManager.getCallManager().isVideo()) {
                        binding.videoCallStateText.setText(getString(R.string.phone_stats_video_preparing));
                    } else {
                        binding.voiceCallStateText.setText(getString(R.string.phone_stats_voice_preparing));
                    }
                }
                break;
                case CallingState_Outgoing_Calling: {
                    //隐藏时间
                    binding.videoCallTimeText.setVisibility(View.GONE);
                    binding.voiceCallTimeText.setVisibility(View.GONE);
                    makeContentLayoutVisible(true, true, false);
                    if (CallManager.getCallManager().isVideo()) {
                        //显示本地视频
                        binding.videoCallBigVideoView.removeAllViews();
                        SurfaceView surfaceView = RtcEngine.CreateRendererView(this);
                        binding.videoCallBigVideoView.addView(surfaceView);
                        CallManager.getCallManager().showLocalVideoToView(surfaceView);
                    }
                    if (CallManager.getCallManager().isVideo()) {
                        binding.videoCallStateText.setText(getString(R.string.phone_stats_accept_yaoqing));
                    } else {
                        binding.voiceCallStateText.setText(getString(R.string.phone_stats_accept_yaoqing));
                    }
                }
                break;
                case CallingState_Incoming_Waiting: {
                    //隐藏时间
                    binding.videoCallTimeText.setVisibility(View.GONE);
                    binding.voiceCallTimeText.setVisibility(View.GONE);
                    makeContentLayoutVisible(true, false, true);
                    if (CallManager.getCallManager().isVideo()) {
                        binding.toolbarIncomingAccept.setImageResource(R.mipmap.call_jieting_video);
                        binding.videoCallStateText.setText(getString(R.string.phone_stats_video_yaoqing));
                    } else {
                        binding.toolbarIncomingAccept.setImageResource(R.mipmap.call_jieting);
                        binding.voiceCallStateText.setText(getString(R.string.phone_stats_voice_yaoqing));
                    }
                }
                break;
                case CallingState_Incoming_Prepare: {
                    //隐藏时间
                    binding.videoCallTimeText.setVisibility(View.GONE);
                    binding.voiceCallTimeText.setVisibility(View.GONE);
                    makeContentLayoutVisible(true, false, true);
                    if (CallManager.getCallManager().isVideo()) {
                        binding.toolbarIncomingAccept.setImageResource(R.mipmap.call_jieting_video);
                        binding.videoCallStateText.setText(getString(R.string.phone_stats_video_preparing));
                    } else {
                        binding.toolbarIncomingAccept.setImageResource(R.mipmap.call_jieting);
                        binding.voiceCallStateText.setText(getString(R.string.phone_stats_voice_preparing));
                    }
                }
                break;
                case CallingState_Canceled: {
                    //隐藏时间
                    binding.videoCallTimeText.setVisibility(View.GONE);
                    binding.voiceCallTimeText.setVisibility(View.GONE);
                    makeContentLayoutVisible(true, false, false);
                    if (CallManager.getCallManager().isVideo()) {
                        binding.videoCallStateText.setText(getString(R.string.phone_stats_video_cancle));
                    } else {
                        binding.voiceCallStateText.setText(getString(R.string.phone_stats_voice_cancle));
                    }
                }
                break;
                case CallingState_Canceled_2_Timeout: {
                    //隐藏时间
                    binding.videoCallTimeText.setVisibility(View.GONE);
                    binding.voiceCallTimeText.setVisibility(View.GONE);
                    makeContentLayoutVisible(true, false, false);
                    if (CallManager.getCallManager().isVideo()) {
                        binding.videoCallStateText.setText(getString(R.string.phone_stats_unresponse));
                    } else {
                        binding.voiceCallStateText.setText(getString(R.string.phone_stats_unresponse));
                    }
                }
                break;
                case CallingState_C2C_Canceled: {
                    //隐藏时间
                    binding.voiceCallTimeText.setVisibility(View.GONE);
                    binding.videoCallTimeText.setVisibility(View.GONE);
                    makeContentLayoutVisible(true, false, false);
                    if (CallManager.getCallManager().isVideo()) {
                        binding.videoCallStateText.setText(getString(R.string.phone_stats_video_cancle));
                    } else {
                        binding.voiceCallStateText.setText(getString(R.string.phone_stats_voice_cancle));
                    }
                }
                break;
                case CallingState_In_Calling: {
                    //视频通话中，隐藏视频相关的头像、昵称等
                    binding.videoCallHeaderImageView.setVisibility(View.GONE);
                    binding.videoCallDisplaynameText.setVisibility(View.GONE);
                    makeContentLayoutVisible(true, true, false);
                    if (CallManager.getCallManager().isVideo()) {
                        binding.videoCallStateText.setText("");
                        binding.videoCallTimeText.setText("00:00");
                        binding.videoCallBigVideoView.removeAllViews();
                        binding.videoCallSmallVideoView.removeAllViews();

                        //显示远程视频
                        SurfaceView surfaceView = RtcEngine.CreateRendererView(this);
                        binding.videoCallBigVideoView.addView(surfaceView);
                        CallManager.getCallManager().showRemoteVideoToView(surfaceView);

                        //显示本地视频
                        surfaceView = RtcEngine.CreateRendererView(this);
                        binding.videoCallSmallVideoView.addView(surfaceView);
                        CallManager.getCallManager().showLocalVideoToView(surfaceView);
                    } else {
                        binding.voiceCallStateText.setText("");
                        binding.voiceCallTimeText.setText("00:00");
                    }
                }
                break;
                case CallingState_Call_End: {
                    makeContentLayoutVisible(true, false, false);
                    if (CallManager.getCallManager().isVideo()) {
                        binding.videoCallStateText.setText(getString(R.string.phone_stats_video_finish));
                        binding.videoCallTimeText.setText("00:00");
                    } else {
                        binding.voiceCallStateText.setText(getString(R.string.phone_stats_voice_finish));
                        binding.voiceCallTimeText.setText("00:00");
                    }
                }
                break;
                default:
                    break;
            }
        } else {
            finish();
        }
    }

    public void resetCallingTime() {
        if (CallManager.getCallManager().isVideo()) {
            binding.videoCallStateText.setText(CallManager.getCallManager().callDisplayTime());
        } else {
            binding.voiceCallStateText.setText(CallManager.getCallManager().callDisplayTime());
        }
    }

    public void resetSpeakerBtn() {
        if (CallManager.getCallManager().hasHeadset()) {
            binding.toolbarAudioSpeaker.setEnabled(false);
            binding.toolbarAudioSpeaker.setImageResource(R.mipmap.call_speaker_close);
        } else {
            binding.toolbarAudioSpeaker.setEnabled(true);
            if (CallManager.getCallManager().isEnableSpeaker()) {
                binding.toolbarAudioSpeaker.setImageResource(R.mipmap.call_speaker_open);
            } else {
                binding.toolbarAudioSpeaker.setImageResource(R.mipmap.call_speaker_close);
            }
        }
    }

    public void resetC2CUserUI() {
        if (CallManager.getCallManager().isVideo()) {//视频
            UserInfo user = CallManager.getCallManager().c2cUser();
            if (user != null) {
                binding.videoCallDisplaynameText.setText(user.displayName());
                //头像&背景
                binding.videoCallHeaderImageView.showUser(user, 240);
                if (user.profile_photo != null && user.profile_photo.isSmallPhotoDownloaded()) {
                    Blurry.with(this).from(BitmapFactory.decodeFile(user.profile_photo.localSmallPath())).into(binding.bkImageView);
                }
            } else {
                long userId = CallManager.getCallManager().c2cUserId();
                binding.videoCallDisplaynameText.setText("" + userId);
                //本地头像
                binding.videoCallHeaderImageView.showName("" + userId);
                //请求用户信息
                requestUserInfo(userId);
            }
        } else {//语音
            UserInfo user = CallManager.getCallManager().c2cUser();
            if (user != null) {
                binding.voiceCallDisplaynameText.setText(user.displayName());
                //头像&背景
                binding.voiceCallHeaderImageView.showUser(user, 240);
                if (user.profile_photo != null && user.profile_photo.isSmallPhotoDownloaded()) {
                    Blurry.with(this).from(BitmapFactory.decodeFile(user.profile_photo.localSmallPath())).into(binding.bkImageView);
                }
            } else {
                long userId = CallManager.getCallManager().c2cUserId();
                binding.voiceCallDisplaynameText.setText("" + userId);
                //本地头像
                binding.voiceCallHeaderImageView.showName("" + userId);
                //请求用户信息
                requestUserInfo(userId);
            }
        }
    }

    private void requestUserInfo(long userId) {
        TelegramManager.getTelegramManager().requestContactInfo(this, userId, new TgResultBlock<UserInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, UserInfo obj) {
                if (obj != null) {
                    resetC2CUserUI();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbarAudioSpeaker: {//麦克风
                if (CallManager.getCallManager().hasHeadset()) {
                    ToastUtils.showShort(getString(R.string.phone_stats_headset));
                } else {
                    CallManager.getCallManager().enableSpeaker(!CallManager.getCallManager().isEnableSpeaker());
                }
                resetSpeakerBtn();
            }
                break;
            case R.id.iv_bar_back:
                CallManager.getCallManager().showSmallTopView();
                onBackPressed();
                break;
            case R.id.toolbarAudioMute://静音
                CallManager.getCallManager().muteLocalAudio();
                break;
            case R.id.toolbarAudioHangup://挂断
                CallManager.getCallManager().endCurrentCall();
                break;
            case R.id.toolbarVideoToggleCamera://前后摄像头切换
                CallManager.getCallManager().toggleCamera();
                break;
            case R.id.toolbarVideoHangup://挂断
                CallManager.getCallManager().endCurrentCall();
                break;
            case R.id.toolbarIncomingAccept://接听
                CallManager.getCallManager().acceptNewCall();
                break;
            case R.id.toolbarIncomingHangup://挂断
                CallManager.getCallManager().endCurrentCall();
                break;
            case R.id.videoCall_SmallVideoView://视频切换
            {
                smallVideoViewIsTarget = !smallVideoViewIsTarget;
                binding.videoCallSmallVideoView.removeAllViews();
                binding.videoCallBigVideoView.removeAllViews();
                if (smallVideoViewIsTarget) {
                    SurfaceView surfaceView = RtcEngine.CreateRendererView(this);
                    binding.videoCallBigVideoView.addView(surfaceView);
                    CallManager.getCallManager().showLocalVideoToView(surfaceView);

                    surfaceView = RtcEngine.CreateRendererView(this);
                    binding.videoCallSmallVideoView.addView(surfaceView);
                    CallManager.getCallManager().showRemoteVideoToView(surfaceView);
                } else {
                    SurfaceView surfaceView = RtcEngine.CreateRendererView(this);
                    binding.videoCallBigVideoView.addView(surfaceView);
                    CallManager.getCallManager().showRemoteVideoToView(surfaceView);

                    surfaceView = RtcEngine.CreateRendererView(this);
                    binding.videoCallSmallVideoView.addView(surfaceView);
                    CallManager.getCallManager().showLocalVideoToView(surfaceView);
                }
            }
            break;
        }
    }


    public void changeAudioMute() {
        if (CallManager.getCallManager().isMuteLocalAudio()) {
            binding.toolbarAudioMute.setImageResource(R.mipmap.call_mute_open);
        } else {
            binding.toolbarAudioMute.setImageResource(R.mipmap.call_mute_close);
        }
    }
}
